package pers.hl.module_main.mine

import android.graphics.drawable.Drawable
import android.os.Bundle
import android.text.InputFilter
import android.text.InputType
import android.text.TextUtils
import android.view.View
import android.widget.EditText
import android.widget.LinearLayout
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import kotlinx.android.synthetic.main.item_rv_common_edit.view.*
import pers.hl.common.base.BaseVBVMActivity
import pers.hl.common.base.ext.showMessage
import pers.hl.common.ui.CommonTextWatcher
import pers.hl.common.ui.DrawableTextView
import pers.hl.common.utils.MyUtils
import pers.hl.lib_global.common.GlideUtils
import pers.hl.lib_global.common.MMKVHelper
import pers.hl.lib_global.model.bean.User
import pers.hl.lib_global.model.enums.FileType
import pers.hl.module_main.CommonEditActivity
import pers.hl.module_main.R
import pers.hl.module_main.common.BaseLibQuickAdapter
import pers.hl.module_main.common.CommonDialog
import pers.hl.module_main.databinding.ActivityUserHomeBinding
import pers.hl.module_main.databinding.ItemRvMineHeaderBinding

class UserHomeActivity : BaseVBVMActivity<ActivityUserHomeBinding, MineViewModel>() {

    private lateinit var mUser: User
    private var userId: Int = -1
    private var isMySelf = false

    private lateinit var headerView: View
    private lateinit var headerBinding: ItemRvMineHeaderBinding
    private lateinit var mAdapter: BaseLibQuickAdapter<CommonEditActivity.EditBean, BaseViewHolder>

    private var isFollow = false

    companion object {
        const val KEY_DATA_USER_ID = "key_data_user_id"
        const val KEY_CAN_EDIT = "key_can_edit"
    }

    override fun initParams() {
        intent?.apply {
            userId = getIntExtra(KEY_DATA_USER_ID, -1)
            if (userId == -1) {
                showMessage("参数错误")
                finish()
            }
            isMySelf = userId == MMKVHelper.getUser()!!.userId
            if (isMySelf) {
                mUser = MMKVHelper.getUser()!!
            }
            val canEdit = getBooleanExtra(KEY_CAN_EDIT, false)
            if (canEdit) {
                isMySelf = canEdit
            }
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        initTitle()
        initRV()
        if (!isMySelf) {
            initHeaderView()
        }
    }

    private fun initTitle() {
        mBinding.apply {
            titleBar.apply {
                tvBarTitle.text = if (isMySelf) "我的资料" else "用户信息"
                ivBarLeft.setOnClickListener {
                    finish()
                }
                if (isMySelf) {
                    ivBarRight.setImageResource(R.drawable.ic_send)
                    ivBarRight.setOnClickListener {
                        mViewModel.updateUser(mUser).observe(this@UserHomeActivity, Observer {
                            showMessage("修改成功")
//                            loadUserInfo()
                        })
                    }
                }

            }

        }
    }

    private fun initHeaderView() {
        headerView = ItemRvMineHeaderBinding.inflate(layoutInflater).root
        mAdapter.setHeaderView(headerView, 0, LinearLayout.VERTICAL)
        headerBinding = ItemRvMineHeaderBinding.bind(headerView)
        headerBinding.apply {
            ivRight.visibility = View.GONE
            ivRight.setOnClickListener {
                if (isFollow) {
                    userId.let { it1 ->
                        mViewModel.unFollow(it1).observe(this@UserHomeActivity, Observer {
                            showMessage("取消关注成功")
                            isFollow = false
                            refreshFollowIcon()
                        })
                    }
                } else {
                    mViewModel.follow(userId).observe(this@UserHomeActivity, Observer {
                        showMessage("关注成功")
                        isFollow = true
                        refreshFollowIcon()
                    })
                }
            }
            llSharing.setOnClickListener {
                showMessage("暂未开放")
            }
            llFollow.setOnClickListener {
                showMessage("暂未开放")
            }
            llFans.setOnClickListener {
                showMessage("暂未开放")
            }
        }
    }

    private fun fillHeaderData() {
        headerBinding.apply {
            userId.let {
                GlideUtils.loadUserAvatar(
                    mContext,
                    ivAvatar,
                    it,
                    R.drawable.ic_personal_center
                )
            }
            tvUserName.text = if (TextUtils.isEmpty(mUser.userName)) "快乐小读者" else mUser.userName
            tvSharingNum.text = mUser.sharingCount
            tvFollowNum.text = mUser.followCount
            tvFansNUm.text = mUser.fansCount
            tvUserName.setDrawableClickListener(object : DrawableTextView.OnDrawableClickListener {
                override fun onRight(right: Drawable) {
                    fetchUserQrCode()
                }
            })
        }
    }

    private fun fetchUserQrCode() {
        MMKVHelper.getUser()?.userId?.let {
            CommonDialog.createQrCodeDialog(mContext, FileType.USER_QR_CODE.value(), it).show()
        }
    }

    private fun initRV() {
        mBinding.apply {
            rvCommonEdit.layoutManager = LinearLayoutManager(mContext)
            mAdapter = object :
                BaseLibQuickAdapter<CommonEditActivity.EditBean, BaseViewHolder>(R.layout.item_rv_common_edit) {
                override fun convert(holder: BaseViewHolder, item: CommonEditActivity.EditBean) {
                    holder.setText(R.id.tvTitle, item.title)
                    holder.setText(R.id.etContent, item.content)
                    holder.setEnabled(R.id.etContent, item.enable)

                    dealSpecialLogic(holder, item)
                    holder.itemView.etContent.apply {
                        setOnClickListener {
                            if (!isMySelf) {
                                return@setOnClickListener
                            }
                            when (item.tagId) {
                                5 -> {
                                    showGenderDialog()
                                }
                            }
                        }
                    }
                }
            }
            rvCommonEdit.adapter = mAdapter
        }
    }

    private fun dealSpecialLogic(holder: BaseViewHolder, item: CommonEditActivity.EditBean) {
        holder.itemView.apply {
            when (item.tagId) {
                4 -> {
                    etContent.inputType = InputType.TYPE_CLASS_NUMBER
                    etContent.filters = arrayOf(InputFilter.LengthFilter(3))
                }
                5 -> etContent.isFocusableInTouchMode = false
                7 -> {
                    etContent.inputType = InputType.TYPE_CLASS_NUMBER
                    etContent.filters = arrayOf(InputFilter.LengthFilter(11))
                }
            }
            val watcher = object : CommonTextWatcher(etContent) {
                override fun textChanged(view: EditText, text: String) {
                    when (item.tagId) {
                        2 -> mUser.userName = text
                        4 -> mUser.useAge = MyUtils.tryParseInt(text)
                        6 -> mUser.userAddr = text
                        7 -> mUser.userTel = text
                    }
                }
            }

            // 在onBindViewHolder()中通过在适当的时机添加或移除Edittext的TextChangedListener来处理数据错乱的问题。
            // 这个适当的时机就是选在Edittext获得焦点的时候添加监听器，失去焦点的时候再移除监听器，这样可以保证数据的正确性。
            etContent.setOnFocusChangeListener { v, hasFocus ->
                if (hasFocus) {
                    etContent.addTextChangedListener(watcher)
                } else {
                    etContent.removeTextChangedListener(watcher)
                }
            }
        }
    }

    private fun showGenderDialog() {
        CommonDialog.createBottomList(
            mContext,
            mutableListOf("男", "女"),
            convertBlock = { holder, item ->
                holder.setText(R.id.tvItem, item)
            },
            onItemClick = { layer, adapter, position, item ->
                layer.dismiss()
                if (position == 0) {
                    mUser.userGender = 1
                }
                if (position == 1) {
                    mUser.userGender = 2
                }
                fillData()
            }).show()
    }

    override fun initData(savedInstanceState: Bundle?) {
//        fillData()
        loadUserInfo()
        checkIsFollowed()
    }

    /**
     * 检查是否已关注
     */
    private fun checkIsFollowed() {
        mViewModel.isFollowed(MMKVHelper.getUser()!!.userId, userId).observe(this, Observer {
            isFollow = it
            refreshFollowIcon()
        })
    }

    private fun refreshFollowIcon() {
        if (isMySelf) {
            return
        }
        headerBinding.ivRight.apply {
            setImageResource(if (isFollow) R.drawable.ic_collect_fill else R.drawable.ic_collect)
            visibility = View.VISIBLE
        }
    }

    private fun loadUserInfo() {
        userId.let {
            mViewModel.fetchUserInfo(it).observe(this, Observer { user ->
                mUser = user
                fillData()
                if (!isMySelf) {
                    fillHeaderData()
                }
            })
        }
    }

    private fun fillData() {
        mUser.apply {
            val list = listOf(
                CommonEditActivity.EditBean(1, "用户编号", userId.toString(), false),
                CommonEditActivity.EditBean(2, "用户名", userName.toString(), isMySelf),
                CommonEditActivity.EditBean(3, "角色", userRoleStr(), false),
                CommonEditActivity.EditBean(4, "年龄", useAge.toString(), isMySelf),
                CommonEditActivity.EditBean(5, "性别", getUserGenderStr()),
                CommonEditActivity.EditBean(6, "地址", userAddr.toString(), isMySelf),
                CommonEditActivity.EditBean(7, "电话", userTel.toString(), isMySelf)
            )
            mAdapter.setList(list)
        }
    }

}